package com.liyunc.demo.service;
/**
 * Copyright (c) 2018-2022 ThunderSoft
 * All Rights Reserved by Thunder Software Technology Co., Ltd and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with ThunderSoft in writing by applicable law.
 */

import com.liyunc.demo.model.dto.RoleInfoDto;
import com.liyunc.demo.model.entity.RoleInfo;
import com.liyunc.demo.service.base.BaseService;
import com.liyunc.demo.utils.ToDtoUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.security.RolesAllowed;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author
 * @version 1.0
 * @file
 * @brief
 * @details
 * @date 2022-02-17
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-02-17                       Created
 */
@Service
public class RoleService extends BaseService {

    /**
     * 给用户授权.
     */
    @RolesAllowed({"ROLE_ADMIN"})
    public Optional<RoleInfoDto> setRoleWithProject(long userId, long projectId, int key) {
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setKey(key);
        return Optional.of(roleInfoRepository.saveAndFlush(roleInfo))
            .map(ToDtoUtils::forInfoEntity);
    }

    /**
     * 删除用户权限.
     */
    @RolesAllowed({"ROLE_ADMIN"})
    public Optional<RoleInfoDto> deleteRoleWithProject(long userId, long projectId) {
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setKey(0);
        return Optional.of(roleInfoRepository.saveAndFlush(roleInfo))
            .map(ToDtoUtils::forInfoEntity);
    }

    /**
     * 根据用户id查询访问权限的项目.
     */
    public List<RoleInfoDto> getProjectListWithRoleByUserId(
        final int startIndex,
        final int pageSize,
        final long userId) {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(startIndex, pageSize, sort);
        Specification<RoleInfo> specification = (root, query, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.equal(root.get("userId"), userId);
            return criteriaBuilder.and(predicate);
        };
        return roleInfoRepository
            .findAll(specification, pageable)
            .stream()
            .map(ToDtoUtils::forInfoEntity)
            .collect(Collectors.toList());
    }
}
